<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="good in cartGoods" :key="good.id">
          <li class="cart-list-con1">
            <!--
                当前的v-model出现了脏数据的问题
                不能使用v-model
                v-model不支持计算属性传参

                v-model后只能跟在vue中定义的数据
            -->
            <input  type="checkbox" name="chk_list"
                    :checked="good.isChecked === 1"
                    @change="changeChecked(good)">
          </li>
          <li class="cart-list-con2">
            <img :src="good.imgUrl">
            <div class="item-msg">{{good.skuName}}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{good.skuPrice}}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="updateNumFn(good,-1)">-</a>
            <!--当前的v-model出现了脏数据的问题-->
            <input autocomplete="off" type="text"
                   @input="valVerify"
                   @change="updateNumFn(good,$event.target.value*1 -good.skuNum,$event)"
                   minnum="1" class="itxt" :value="good.skuNum">
            <a href="javascript:void(0)" class="plus" @click="updateNumFn(good,1)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{good.skuNum * good.skuPrice}}</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click="del(good)">删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll">
        <span> 全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="delAllChecked">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span style="color: deeppink;font-weight: bold">{{totalNum}}</span> 件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{totalPrice}}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/Trade">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapActions,mapState,mapGetters} from "vuex"
  export default {
    name: 'ShopCart',
    computed:{
        ...mapState({
            cartGoods:state=>state.cart.cartGoods
        }),
        ...mapGetters(["totalNum","totalPrice"]),
        //全选全不选
        checkAll:{
            get(){
                return this.$store.getters.checkAll
            },
            async set(newVal){
                // newVal: 全选按钮的最新状态
                try{
                    await this.checkAllFn(newVal)
                    //当代码执行到当前行 代表checkAllFn执行成功
                    //将数据库中最新的数据同步到仓库
                    this.getGoodsFromCart()
                }catch (e) {
                  alert("全选操作失败")
                }
            }
        }
    },
    methods:{
        ...mapActions(["getGoodsFromCart","delGoodsFromCart","addGoodsToCart",
            "updateCheckedForCartGood","checkAllFn","delAllCheckedFn"]),
        //改变对应数据的选中状态
        async changeChecked(good){
          //对应商品的id
          const skuId = good.skuId;
          //将对应商品选中状态变为哪个值 0:不选中 1:选中
          const isChecked = good.isChecked === 1 ? 0 : 1;

          try {
              const error = await this.updateCheckedForCartGood({skuID:skuId,isChecked});
              if(error){
                  alert("勾选操作失败")
              }else{
                  //重新请求购物车数据
                  this.getGoodsFromCart()
              }
          }catch (e) {
              alert("网络异常")
          }
        },
        //实现单个删除功能
        async del(good){
            if(window.confirm(`是否删除${good.skuName}`)){
                //转发action 进而去发送请求
                try{
                    await this.delGoodsFromCart(good.skuId)
                    this.getGoodsFromCart()
                }catch (e) {
                    //请求成功了 但删除操作出了异常
                    alert(e.message)
                }
            }
        },
        //删除所有选中的商品
        async delAllChecked(){
            if(window.confirm(`是否删除`)){
                try{
                    await this.delAllCheckedFn()
                    this.getGoodsFromCart()
                }catch (e) {
                    alert(e.message)
                }
            }
        },
        //更新购物车商品的数量
        async updateNumFn(good,updateNum,event){

            //updateNum: $event.target.value*1 -good.skuNum
            // 当对应商品的总数量 >= 1 时 我们才需要去发请求
            //总数量  $event.target.value*1
            const total = updateNum + good.skuNum;
            if (total >= 1){
                //updateNum : 代表的是新增或减少的数量
                const error = await this.addGoodsToCart({skuid:good.skuId,skuNum:updateNum})
                if(error){
                    alert(error)
                }else{
                    //请求成功 并且 新增操作(也有可能是对数量的修改)也成功
                    this.getGoodsFromCart()
                }
            }else{
                //能进if说明是在输入框中输入数据的
                //输入了一个小于1的值
                //输入了一个非法的值
                if(event){
                    event.target.value = good.skuNum
                }
            }
        },
        // 验证输入框数据的
        valVerify(event){
            let val = event.target.value;
            //命中所有的非数字 以及以0开头的0
            // 000123.abc.7.9  ==> 12379
            let reg = /^0+|\D+/g;
            event.target.value = val.replace(reg,"")
        }
    },
    mounted(){
        this.getGoodsFromCart()
    }
  }
</script>

<style lang="less" scoped>
  .cart {
    width: 1200px;
    margin: 0 auto;

    h4 {
      margin: 9px 0;
      font-size: 14px;
      line-height: 21px;
    }

    .cart-main {
      .cart-th {
        background: #f5f5f5;
        border: 1px solid #ddd;
        padding: 10px;
        overflow: hidden;

        &>div {
          float: left;
        }
        .cart-th1 {
          width: 5%;

          input {
            vertical-align: middle;
          }

          span {
            vertical-align: middle;
          }
        }
        .cart-th2 {
          width: 35%;
        }
        .cart-th3,
        .cart-th4,
        .cart-th5,
        .cart-th6 {
          width: 15%;

        }
      }

      .cart-body {
        margin: 15px 0;
        border: 1px solid #ddd;

        .cart-list {
          padding: 10px;
          border-bottom: 1px solid #ddd;
          overflow: hidden;

          &>li {
            float: left;
          }

          .cart-list-con1 {
            width: 5%;
          }

          .cart-list-con2 {
            width: 35%;

            img {
              width: 82px;
              height: 82px;
              float: left;
            }

            .item-msg {
              float: left;
              width: 150px;
              margin: 0 10px;
              line-height: 18px;
            }
          }

          .cart-list-con4 {
            width: 15%;

          }

          .cart-list-con5 {
            width: 15%;

            .mins {
              border: 1px solid #ddd;
              border-right: 0;
              float: left;
              color: #666;
              width: 6px;
              text-align: center;
              padding: 8px;
            }

            input {
              border: 1px solid #ddd;
              width: 40px;
              height: 33px;
              float: left;
              text-align: center;
              font-size: 14px;
            }

            .plus {
              border: 1px solid #ddd;
              border-left: 0;
              float: left;
              color: #666;
              width: 6px;
              text-align: center;
              padding: 8px;
            }
          }

          .cart-list-con6 {
            width: 15%;

            .sum {
              font-size: 16px;
            }
          }

          .cart-list-con7 {
            width: 15%;

            a {
              color: #666;
            }
          }
        }
      }
    }

    .cart-tool {
      overflow: hidden;
      border: 1px solid #ddd;

      .select-all {
        padding: 10px;
        overflow: hidden;
        float: left;

        span {
          vertical-align: middle;
        }

        input {
          vertical-align: middle;
        }
      }

      .option {
        padding: 10px;
        overflow: hidden;
        float: left;

        a {
          float: left;
          padding: 0 10px;
          color: #666;
        }
      }

      .money-box {
        float: right;

        .chosed {
          line-height: 26px;
          float: left;
          padding: 0 10px;
        }

        .sumprice {
          width: 200px;
          line-height: 22px;
          float: left;
          padding: 0 10px;

          .summoney {
            color: #c81623;
            font-size: 16px;
          }
        }

        .sumbtn {
          float: right;

          a {
            display: block;
            position: relative;
            width: 96px;
            height: 52px;
            line-height: 52px;
            color: #fff;
            text-align: center;
            font-size: 18px;
            font-family: "Microsoft YaHei";
            background: #e1251b;
            overflow: hidden;
          }
        }
      }
    }
  }
</style>